<template>
  <div>
    <div class="am-u-sm-12 am-u-md-12 am-u-lg-12">
      <div class="widget am-cf">
        <div class="widget-head am-cf">
          <div class="widget-title  am-cf">优惠卷码</div>
        </div>
        <div class="widget-body  am-fr">

          <div class="am-u-sm-12 am-form ">

            <div class="am-u-sm-12 am-u-md-12 am-u-lg-3">
              <div class="am-form-group">
                <select2 v-model="query.areaTeamId" :options="areaTeams">
                  <option value="">区域</option>
                </select2>
              </div>
            </div>

            <div class="am-u-sm-12 am-u-md-12 am-u-lg-3">
              <div class="am-form-group">
                <select2 v-model="query.enableStatus" >
                  <option value="">启用状态</option>
                  <option value="0">禁用</option>
                  <option value="1">启用</option>
                </select2>
              </div>
            </div>

        <!--    <div class="am-u-sm-12 am-u-md-12 am-u-lg-3">
              <div class="am-form-group">
                <select2 v-model="query.effectStatus" >
                  <option value="">生效状态</option>
                  <option value="0">失效</option>
                  <option value="1">生效</option>
                </select2>
              </div>
            </div>-->

            <div class="am-u-sm-12 am-u-md-12 am-u-lg-3">
              <div class="am-form-group">
                <select2 v-model="query.usedStatus" >
                  <option value="">使用状态</option>
                  <option value="0">未使用</option>
                  <option value="1">已使用</option>
                </select2>
              </div>
            </div>


            <div class="am-u-sm-12 am-u-md-12 am-u-lg-3">
              <div class="am-form-group">
                <input type="text" v-model="query.name" placeholder="优惠券名称"/>
              </div>
            </div>

            <div class="am-u-sm-12 am-u-md-12 am-u-lg-3">
              <div class="am-form-group">
                <input type="text" v-model="query.code" placeholder="优惠券码"/>
              </div>
            </div>
            <div class="am-u-sm-12 am-u-md-12 am-u-lg-3">
              <div class="am-form-group">
                <select2 v-model="query.discountType" >
                  <option value="">优惠类型</option>
                  <option value="0">额度优惠</option>
                  <option value="1">折扣优惠</option>
                </select2>
              </div>
            </div>
            <div class="am-u-sm-12 am-u-md-12 am-u-lg-3">
              <div class="am-form-group">
                <el-date-picker
                  v-model="query.time"
                  type="daterange"
                  placeholder="优惠券生成时间">
                </el-date-picker>
              </div>
            </div>

            <div class="am-u-sm-12 am-u-md-12 am-u-lg-3 am-u-end">
              <div class="am-form-group">
                <button type="button" class="am-btn am-btn-default am-btn-success"
                        @click="search"><span class="am-icon-search"></span>查询

                </button>
              </div>
            </div>

            <div class="am-u-sm-12 am-u-md-12 am-u-lg-12">
              <div class="am-form-group am-btn-group-xs">
                <button type="button" class="am-btn am-btn-default am-btn-success"
                        @click="handleUpdateStatus(1)" v-if="hasPermission('enable_disable')"><span></span>批量启用
                </button>
                <button type="button" class="am-btn am-btn-default am-btn-success"
                        @click="handleUpdateStatus(0)" v-if="hasPermission('enable_disable')"><span></span>批量禁用
                </button>
                <button type="button" class="am-btn am-btn-default am-btn-success"
                        @click="$router.push('/main/discount/discountCode/add')" v-if="hasPermission('create')"><span></span>生成优惠券码
                </button>
                <button type="button" class="am-btn am-btn-default am-btn-success"
                        @click="handleExport" v-if="hasPermission('export')"><span></span>导出
                </button>
              </div>
            </div>

          </div>

          <div class="am-u-sm-12">
            <el-table
              :data="tableData"
              border
              stripe
              @selection-change="handleSelectionChange"
              style="min-width: 100%">
              <el-table-column
                type="selection"
                fixed
                width="55">
              </el-table-column>

              <el-table-column
                prop="name"
                label="优惠券名称"
                min-width="120">
              </el-table-column>
              <el-table-column
                prop="code"
                label="优惠券码"
                min-width="120">
              </el-table-column>
              <el-table-column
                prop="name"
                label="使用状态"
                min-width="120">
                <template scope="scope">
                  <div>{{scope.row.usedStatus === '1' ? '已使用': '未使用'}}</div>
                </template>
              </el-table-column>
              <el-table-column
                prop="name"
                label="优惠类型"
                min-width="120">
                <template scope="scope">
                  <div>{{scope.row.discountType === '1' ? '折扣优惠': '额度优惠'}}</div>
                </template>
              </el-table-column>
              <el-table-column
                label="优惠额度"
                min-width="120">
                <template scope="scope">
                  <!-- <span v-if="scope.row.discountType==0">{{scope.row.discountAmount}}</span>
                  <span v-if="scope.row.discountType==1">{{scope.row.discountRate}}</span> -->
                  <span>{{scope.row.discountAmount}}</span>
                </template>
              </el-table-column>
              <!-- <el-table-column
                prop="discountAmount"
                label="扣减额度"
                min-width="120">
              </el-table-column> -->
              <el-table-column
                prop="orderThresholdAmount"
                label="最低消费"
                min-width="120">
              </el-table-column>
              <el-table-column
                prop="effectiveStartTime"
                label="生效日期"
                min-width="120">
                <template scope="scope">
                  <div>{{scope.row.effectiveStartTime | formatTime}}</div>
                </template>
              </el-table-column>
              <el-table-column
                prop="effectiveEndTime"
                label="失效日期"
                min-width="120">
                <template scope="scope">
                  <div>{{scope.row.effectiveEndTime | formatTime}}</div>
                </template>
              </el-table-column>
              <el-table-column
                prop="name"
                label="启用状态"
                min-width="120">
                 <template scope="scope">
                  <div>{{scope.row.enableStatus === '1' ? '启用': '禁用'}}</div>
                </template>
              </el-table-column>
   <!--           <el-table-column
                prop="name"
                label="生效状态"
                min-width="120">
                 <template scope="scope">
                  <div>{{scope.row.effectiveStartTime < new Date().getTime() < scope.row.effectiveEndTime ? '生效': '失效'}}</div>
                </template>
              </el-table-column>-->
              <el-table-column
                prop="name"
                label="适用区域"
                min-width="120">
                <template scope="scope">
                  <div>
                    {{areaTeamName(scope.row.areaTeamId)}}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="name"
                label="适用期数"
                min-width="120">
                <template scope="scope">
                  <div>
                    <el-tooltip  effect="light" placement="top">
                      <div class="content-tooltip" slot="content">{{periodNames(scope.row.areaTeamId,scope.row.periodIds).replace(/,/g, '\n')}}</div>
                      <a>查看</a>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="name"
                label="适用业务组"
                min-width="120">
                <template scope="scope">
                  <div>
                    <el-tooltip  effect="light" placement="top">
                      <div class="content-tooltip" slot="content">{{busTeamNames(scope.row.areaTeamId,scope.row.busTeamIds).replace(/,/g, '\n')}}</div>
                      <a>查看</a>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="name"
                label="适用课程"
                min-width="120">
                <template scope="scope">
                  <div>
                    <el-tooltip effect="light" placement="top">
                      <div class="content-tooltip" slot="content">{{courseNames(scope.row.areaTeamId,scope.row.courseTemplateIds).replace(/,/g, '\n')}}</div>
                      <a>查看</a>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="name"
                label="适用年级"
                min-width="120">
                <template scope="scope">
                  <div>
                    <el-tooltip  effect="light" placement="top">
                      <div class="content-tooltip" slot="content">{{gradeNames(scope.row.gradeIds).replace(/,/g, '\n')}}</div>
                      <a>查看</a>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="name"
                label="适用科目"
                min-width="120">
                <template scope="scope">
                  <div>
                    <el-tooltip  effect="light" placement="top">
                      <div class="content-tooltip" slot="content">{{subjectNames(scope.row.subjectIds).replace(/,/g, '\n')}}</div>
                      <a>查看</a>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="createTime"
                label="优惠券生成时间"
                min-width="120">
                <template scope="scope">
                  <div>{{scope.row.createTime | formatDate}}</div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="am-u-lg-12 am-cf">

            <div class="am-fr">
              <pagination v-bind:total="total" v-bind:pageNo="pageNo" v-bind:pageSize="pageSize"
                          @paging="loadTableData"/>
            </div>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script>

  import Pagination from '../base/Pagination'
  import moment from 'moment'
  import util from "../../lib/util"
  import io from '../../lib/io'

  export default{
    data: function () {
      return {
        tableData: [],
        total: 0,
        pageSize: 10,
        pageNo: 1,
        productList: {},
        templateCourseList: {},
        periods: {},
        query: {
          areaTeamId :'',
          enableStatus :'',
          effectStatus :'',
          usedStatus :'',
          name :'',
          code :'',
          startCreateTime :'',
          endCreateTime :'',
          discountType:'',
          time:[]
        },
      }
    },
    components: {
      Pagination
    },
    computed: {
      grades: function () {
        return this.$root.config.grades || []
      },
      subjects: function () {
        return this.$root.config.subjects || []
      },
      areaTeams: function () {
        var options = ( this.$root.config.areaTeams || [] )
          .map(function (item) {
            return {value: item.areaTeamId, text: item.name}
          })
        return options
      },
      busTeams: function () {
        var options = ( ( this.query.areaTeamId  ) ? ( this.$root.config.groupBusTeams[this.query.areaTeamId] || [] ) : [] )
          .map(function (item) {
            return {value: item.busTeamId, text: item.name}
          })
        this.query.busTeamId = ''
        return options
      }
    },
    watch: {
      'query.time' (newVal) {
          console.log(newVal)
        if (newVal && newVal.length === 2) {
          this.query.startCreateTime = newVal[0] ? util.formatDate(newVal[0]): ''
          this.query.endCreateTime = newVal[1] ?util.formatDate(newVal[1]): ''
        }
      }
    },
    mounted: function () {
      $(window).smoothScroll()
    },
    created: function () {
      this.loadTableData(this.pageNo);
      // console.log(this.areaTeams)
    },
    methods: {
      areaTeamName (areaTeamId) {
        let name = ''
        this.$root.config.areaTeams.map(val => {
          if (areaTeamId === val.areaTeamId) {
            name =  val.name
          }
        })
        return name
      },
      courseNames (areaTeamId, courseTemplateIds) {
        let list = this.templateCourseList[areaTeamId]
        let names = []
        // console.log(list,courseTemplateIds)
        list.map(val => {
          courseTemplateIds && courseTemplateIds.split(',').map(id => {
            if (val.courseTemplateId === id) {
              names.push(val.courseName)
            }
          })
        })
        return names.join(',')
      },
      periodNames (areaTeamId, periodIds) {
        let list = this.periods[areaTeamId]
        let names = []
        // console.log(list,periodIds)
        list.map(val => {
          periodIds && periodIds.split(',').map(id => {
            if (val.periodId === id) {
              names.push(val.periodName)
            }
          })
        })
        return names.join(',')
      },
      busTeamNames (areaTeamId, busTeamIds) {
        let busTeamNames = []
        console.log("xxx",this.$root.config.groupBusTeams[areaTeamId])
        this.$root.config.groupBusTeams[areaTeamId] && this.$root.config.groupBusTeams[areaTeamId].map(val => {
          busTeamIds && busTeamIds.split(',').map(busTeamId => {
            if (val.busTeamId === busTeamId) {
              busTeamNames.push(val.name)
            }
          })
        })
        return busTeamNames.join(',')
      },
      subjectNames (subjectIds) {
        let subjectNames = []
        this.$root.config.subjects.map(val => {
          subjectIds && subjectIds.split(',').map(subjectId => {
            if (val.subjectId === subjectId) {
              subjectNames.push(val.subjectName)
            }
          })
        })
        return subjectNames.join(',')
      },
      gradeNames (gradeIds) {
        let gradeNames = []
        this.$root.config.grades.map(val => {
          gradeIds && gradeIds.split(',').map(gradeId => {
            if (val.gradeId === gradeId) {
              gradeNames.push(val.gradeName)
            }
          })
        })
        return gradeNames.join(',')
      },
      handleSelectionChange (value) {
        this.discountCodeIds = []
        console.log(value)
        value.map(val => {
          this.discountCodeIds.push(val.discountCodeId)
        })
      },
      handleUpdateStatus (enableStatus) {
        if (this.discountCodeIds && this.discountCodeIds.length === 0) {
          this.$alert('至少选择一条记录')
          return
        }
        io.post(io.updateDiscountEnable,{discountCodeIds: this.discountCodeIds, enableStatus: enableStatus}, (ret)=> {
          if (ret.success) {
            this.$toast('操作成功')
            this.loadTableData()
          } else {
            _this.$alert(ret.desc)
          }
        })
      },
      handleExport () {

        io.downloadFile(io.exportDiscountCodeList,  this.query,  (ret)=> {
          if (ret.success) {
          } else {
            this.$alert(ret.desc)
          }
        })
      },
      search:function(){
        this.loadTableData(1)
      },
      loadTableData: function (pageNo) {
        var _this = this
        _this.pageNo = pageNo || _this.pageNo || 1
        io.post(io.discountCodeList, $.extend({
          pageNo: _this.pageNo,
          pageSize: _this.pageSize
        }, _this.query), function (ret) {
          if (ret.success) {
            _this.total = ret.data.total
            let areaTeamIds = []
            setTimeout(function () {
              _this.tableData = ret.data.list
            }, 500)
            ret.data.list.map(val => {
              areaTeamIds.push(val.areaTeamId)
            })
            console.log(areaTeamIds)
            areaTeamIds = _this.unique(areaTeamIds)
            console.log(areaTeamIds)
            areaTeamIds.map(val => {
              _this.loadProductData(val)
              _this.loadTemplateCourseData(val)
              _this.loadPeriodData(val)
            })
          } else {
            _this.$alert(ret.desc)
          }
        })
      },
      unique(array) {
        var res = array.filter(function(item, index, array){
          return array.indexOf(item) === index;
        })
        return res;
      },
      loadProductData: function (areaTeamId) {
        var _this = this
        io.post(io.apiAdminBaseProductListForAreaTeam, {
          areaTeamId : areaTeamId
        }, function (ret) {
          if (ret.success) {
            _this.productList[areaTeamId] = ret.data
          } else {
            _this.$alert(ret.desc)
          }
        })
      },
      loadTemplateCourseData: function (areaTeamId, courseTemplateIds) {
        var _this = this
        io.post(io.apiAdminBaseCourseTemplateListForAreaTeam, {
          areaTeamId : areaTeamId
        }, function (ret) {
          if (ret.success) {
            _this.templateCourseList[areaTeamId] = ret.data
          } else {
            _this.$alert(ret.desc)
          }
        })
      },
      loadPeriodData: function (areaTeamId) {
        var _this = this
        io.post(io.apiAdminPeriodListForAreaTeam, {
          areaTeamId : areaTeamId
        }, function (ret) {
          if (ret.success) {
            _this.periods[areaTeamId] = ret.data
          } else {
            _this.$alert(ret.desc)
          }
        })
      },
    }
  }
</script>

<style>
  .el-tag+.el-tag {
    margin-left: 10px;
    margin-top: 5px;
  }
</style>
<style scoped lang="less">
  .content-tooltip {
    unicode-bidi: embed;
    white-space: pre;
    font-size: 14px;
    line-height: 1.5;
    max-height: 250px;
    overflow-y: scroll;
  }
</style>
